package com.um.jdy.app.core.manager;

import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.commons.properties.HshChargingProperties;
import com.um.springboot.starter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class OrderRedisTemplate {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    HshChargingProperties hshChargingProperties;


    public void setOrder(String deviceCode, Integer port, OrderEnum.Status status, String orderId) {
        redisTemplate.opsForValue().set("order_"+deviceCode+"_"+port+"_"+status.name(),orderId);
    }

    public void removeOrder(String deviceCode, Integer port, OrderEnum.Status status) {
        redisTemplate.delete("order_"+deviceCode+"_"+port+"_"+status.name());
    }

    public void removeOrder(String deviceCode, Integer port) {
        removeOrder(deviceCode,port,OrderEnum.Status.NotStarted);
        removeOrder(deviceCode,port,OrderEnum.Status.Charging);
    }

    public String getOrder(String deviceCode, Integer port, OrderEnum.Status status){
        return (String)redisTemplate.opsForValue().get("order_"+deviceCode+"_"+port+"_"+status.name());
    }

    /**
     * 判断是否充满
     * @param orderId
     * @param power
     * @return
     */
    public boolean hasChargeFull(String orderId,int power){
        if(power > hshChargingProperties.getChargeFullPower()) {
            redisTemplate.delete("chargeFull_"+orderId);
            return false;
        }
        int num = StringUtil.toInt(redisTemplate.opsForValue().get("chargeFull_"+orderId));
        num ++;
        redisTemplate.opsForValue().set("chargeFull_"+orderId,num);
        log.debug("chargeFull:{}:{}",orderId,num);
        return num > hshChargingProperties.getChargeFullDuration();
    }

    /**
     * 删除充满订单
     * @param orderId
     */
    public void removeChargeFull(String orderId){
        redisTemplate.delete("chargeFull_"+orderId);
    }


    /**
     * 判断端口空闲5次，则停止订单
     * @param deviceCode
     * @param port
     * @return
     */
    public boolean isPortFree(String deviceCode, Integer port){
        int num = StringUtil.toInt(redisTemplate.opsForValue().get("portFree_"+deviceCode+"_"+port));
        num ++;
        redisTemplate.opsForValue().set("portFree_"+deviceCode+"_"+port,num);
        log.debug("portFree:{},{},{}",deviceCode,port,num);
        return num >= 5;
    }


    public void removePortFree(String deviceCode, Integer port){
        redisTemplate.delete("portFree_"+deviceCode+"_"+port);
    }

}
